# InstantSpine searches the provided script for a function named 
#      update_parameters
# taking a single parameter of type type InstantSpine::Core.VertebraDiscAnatomy,
# which describes the anatomy of an individual vertebra (and succ. disc)
# The defined update_parameters function is called any time the user changed one
# of the properties via the GUI; update_parameters can than refresh the anatomy
# properties in an arbitrary way.
#
# anatomy properties of VertebraDiscAnatomy:
#   VertebralBodyHeightPosterior
#   EndplateWidthSuperior
#   EndplateWidthInferior
#   EndplateDepthSuperior
#   EndplateDepthInferior
#   DiscHeight
#   FacetTiltLeftX
#   FacetTiltLeftY
#   FacetTiltRightX
#   FacetTiltRightY
#   FacetWidthLeft
#   FacetWidthRight
#   FacetHeightLeft
#   FacetHeightRight

# Vertebra IDs: 0 (= T1) ... 17 (= S1)
is_thoracal = lambda x: x.VertebraID <= 11

# compute anatomy parameters of vertebra v
def update_parameters(v):
    # independent variable/regressor/predictor
    x = v.VertebralBodyHeightPosterior

    # Kunkel et al. 2010 (Prediction equations for human thoracic and lumbar vertebral morphometry)
    v.EndplateWidthSuperior = 121.65 - 15.403 * x + 0.742 * x**2 - 0.010 * x**3
    v.EndplateWidthInferior = 300.14 - 43.509 * x + 2.206 * x**2 - 0.035 * x**3
    v.EndplateDepthSuperior = -60.076 + 8.983 * x - 0.293 * x**2 + 0.004 * x**3
    v.EndplateDepthInferior = -63.590 + 9.473 * x - 0.300 * x**2 + 0.003 * x**3

    # Kunkel et al. 2011 (Morphometric analysis of the relationships between intervertebral disc and vertebral body heights)
    # anterior disc height
    adh = 298.43 - 46.993 * x + 2.561 * x**2 - 0.045 * x**3
    # estimate median dh based on adh
    v.DiscHeight = 3.500 + 0.453 * adh

    # Kunkel et al. 2011 (Prediction of the human thoracic and lumbar articular facet joint)
    if is_thoracal(v):
        v.FacetTiltLeftX  = 998.88 - 149.7 * x + 8.0381 * x**2 - 0.143 * x**3
        v.FacetTiltRightX = -1084.000 + 160.740 * x - 8.4545 * x**2 + 0.147 * x**3
        v.FacetWidthLeft = 381.760 - 59.777 * x + 3.175 * x**2 - 0.056 * x**3
        v.FacetWidthRight = 244.770 - 36.675 * x + 1.890 * x**2 - 0.032 * x**3
    else:
        v.FacetTiltLeftX = -1384.100 + 260.400 * x - 15.23 * x**2 + 0.292 * x**3
        v.FacetTiltRightX = 895.720 - 180.630 * x + 10.957 * x**2 - 0.217 * x**3
        v.FacetWidthLeft = 240.180 - 35.123 * x + 1.759 * x**2 - 0.029 * x**3
        v.FacetWidthRight = 177.180 - 25.063 * x + 1.233 * x**2 - 0.020 * x**3

    v.FacetTiltLeftY = -629.850 + 106.150 * x - 5.322 * x**2 + 0.089 * x**3
    v.FacetTiltRightY = -468.340 + 81.873 * x - 4.122 * x**2 + 0.070 * x**3
    v.FacetHeightLeft = -4.775 + 4.189 * x - 0.309 * x**2 + 0.007 * x**3
    v.FacetHeightRight = 33.916 - 2.520 * x + 0.068 * x**2 + 0.001 * x**3
